<template>
  <div class="custom-table">
    <el-table
      :data="paginatedData"
      v-loading="loading"
      border
      style="width: 100%"
    >
      <el-table-column width="55">
        <template slot-scope="{ row }">
          <div>
            <input
              v-model="row.checked"
              @change="onCheck(row.id)"
              type="checkbox"
              class="checkboxs"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
      />
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, sizes, total"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        :total="data.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue"

const data = ref([
  { id: 1, name: "John Doe", age: 30, checked: false, img: "" },
  { id: 2, name: "Jane Smith", age: 25, checked: false, img: "" },
  { id: 3, name: "Sam Green", age: 35, checked: false, img: "" }
])
const imgUrl = "http://192.168.18.130:8889/api/saas/admin/file/preview/"
data.value.forEach(item => {
  item.img = imgUrl + "1057228589738496000"
})
const columns = [
  { prop: "id", label: "ID", width: 60 },
  { prop: "name", label: "Name" },
  { prop: "age", label: "Age", width: 80 }
]

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(2)
const pageSizes = [2, 4]
const selectedRow = ref(null)

const onCheck = function(id) {
  console.log(id, "id")
  data.value.forEach(item => {
    item.checked = false
    if (item.id === id) {
      item.checked = true
      selectedRow.value = item
    }
  })
}

// Computed property for paginated data
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.value.slice(start, end)
})

// Handlers for pagination
const handleSizeChange = newSize => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = newPage => {
  currentPage.value = newPage
  console.log(selectedRow.value, "分页时 current page")
}
</script>

<style scoped>
.custom-table {
  width: 100%;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.checkboxs {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
</style>
